package com.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by peak on 2016/1/11.
 */
public class SocketServer {
    public static void main(String[] args) throws Exception{
        ServerSocket server = new ServerSocket(8000);
        Socket socket = null;

        while((socket=server.accept())!=null){
            InputStream in = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);

            StringBuffer buffer = new StringBuffer();
            while(true) {
                int c = reader.read();
                if (c == '\r' || c == '\n' || c==-1) break;
                buffer.append((char)c);
            }
            System.out.println(buffer.toString());

            OutputStream out = socket.getOutputStream();
            requstOuterWebsite(out);

            in.close();
            out.close();
            socket.close();
        }

        server.close();
    }

    public static void requstOuterWebsite(OutputStream out) throws IOException {
        URL url = new URL("http://www.tuicool.com/articles/rINr2m");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestProperty("keep-alive","close");
        InputStream in = conn.getInputStream();

        List<Byte> buffer = new ArrayList<Byte>();

        int n=0;
        while((n=in.read())!=-1){
            out.write(n);
        }

    }
}
